// src/components/RouteConfigExample.js

import React from 'react';
import {
  BrowserRouter as Router,
  Route,
  Link,
} from 'react-router-dom';

/*
Some folks find value in a centralized route config.
有些人在集中式 路由配置（route config） 中找到值。

A route config is just data. React is great at mapping data into components, and <Route> is a component.
路由配置（route config） 只是数据。React 很好地将数据映射到组件（components），而 <Route> 是一个组件（components）。
*/

////////////////////////////////////////////////////////////
// 首先是我们的路由组件
const Main = () => <h2>Main</h2>;
// 三明治组件
const Sandwiches = () => <h2>Sandwiches</h2>;
// 玉米饼组件
const Tacos = ({ routes }) => (
  <div>
    <h2>Tacos</h2>
    <ul>
      <li><Link to="/tacos/bus">Bus</Link></li>
      <li><Link to="/tacos/cart">Cart</Link></li>
    </ul>

    {routes.map((route, i) => (
      <RouteWithSubRoutes key={i} {...route} />
    ))}
  </div>
);

const Bus = () => <h3>Bus</h3>;
const Cart = () => <h3>Cart</h3>;

////////////////////////////////////////////////////////////
/*
然后是我们的路由配置
- '/sandwiches' 路径下，展示 Sandwiches
- '/tacos' 路径下，展示 Tacos
*/
const routes = [
  { path: '/sandwiches',
    component: Sandwiches
  },
  { path: '/tacos',
    component: Tacos,
    routes: [
      { path: '/tacos/bus',
        component: Bus
      },
      { path: '/tacos/cart',
        component: Cart
      }
    ]
  }
];

/*
wrap <Route> and use this everywhere instead, then when sub routes are added to any route it'll work
包裹 <Route> 并将其随处可见，然后当将子路径添加到任何路由时，它将起作用
*/
const RouteWithSubRoutes = (route) => (
  <Route path={route.path} render={props => (
    /*
    pass the sub-routes down to keep nesting
    通过 sub-routes 保持嵌套
    */
    <route.component {...props} routes={route.routes} />
  )} />
);

const RouteConfigExample = () => (
  <div>
    {/* 固定的两个导航链接 */}
    <ul>
      <li><Link to="/tacos">Tacos</Link></li>
      <li><Link to="/sandwiches">Sandwiches</Link></li>
    </ul>

    {/* 子路由循环 */}
    {routes.map((route, i) => (
      <RouteWithSubRoutes key={i} {...route}/>
    ))}
  </div>
);

export default RouteConfigExample;
